String.prototype.trim = function() {
    return this.replace(/(^[\s]*)|([\s]*$)/g, "");
}
String.prototype.lTrim = function() {
    return this.replace(/(^[\s]*)/g, "");
}
String.prototype.rTrim = function() {
    return this.replace(/([\s]*$)/g, "");
}

function getFirstChildByClassName(parentElement, className)
{
    for(var i = 0; i < parentElement.children.length; ++i)
        if(parentElement.children[i].className == className)
            return parentElement.children[i];
        return null;
}

function getElementsByClass(theClass)
{
    var elementArray =[];
    if (document.all) {
        elementArray = document.all;
    } else {
        elementArray = document.getElementsByTagName("*");
    }
    var matchedArray =[];
    var pattern = new RegExp("^" + theClass + "$");
    for (var i = 0; i < elementArray.length; i++) {
        if (pattern.test(elementArray[i].className)) {
            matchedArray[matchedArray.length] = elementArray[i];
        }
    }
    return matchedArray;
};

function fill_blks(ss_data)
{
    var idx;
    var tmp;
    var blk_elements=new Array();

    blk_elements = ss_data.split('#');
    for(idx=0;idx<blk_elements.length;idx++) {
        tmp = blk_elements[idx].trim();
        blk_elements[idx] = tmp;
    }

    if(blk_elements[0] == "")
        return [];
    else
        return blk_elements;
}

function blocks_proc(ss_data)
{
    var block_users = [];
    var block_signature_users = [];
    var block_photos = [];
    var block_images = [];
    var block_forums = [];
    var hide_authors = false; /* not used */
    var simple_read = false; /* not used */
    var block_content = []; /* not used */

    block_users = fill_blks(ss_data.blk_persons);
    block_signature_users = fill_blks(ss_data.blk_signs);
    block_photos = fill_blks(ss_data.blk_heads);
    block_images = fill_blks(ss_data.blk_pics);
    block_forums = fill_blks(ss_data.blk_articles);

    (location.pathname == "/" || location.pathname == "/index.php") && 
    (block_users.length || block_forums.length || hide_authors) && (function ()
    {
        var list = document.getElementsByClassName("top"); //<ul>
        function blockPostInToplist(number, link, author)
        {
            link.innerHTML = "";
            var new_link = link.cloneNode();
            new_link.style.display = "";
            new_link.style.width = number.style.width;
            link.parentElement.insertBefore(new_link, link);
            new_link.appendChild(number);
            author.style.display = "none";
        }
        var filterPosts = function(ul)
        {
            for(var i = 0; i < ul.children.length; ++i)
            {
                var cur_li = ul.children[i];
                var cur_number = cur_li.children[0];
                var cur_link = cur_li.children[1];
                var cur_author = cur_li.children[2];
                if(hide_authors && cur_author)
                {
                    cur_author.style.display = "none";
                    cur_link.style.height = "20px";
                    cur_link.style.width = "300px";
                    cur_link.style.overflow = "hidden";
                    var title = (cur_link.innerText || cur_link.textContent);
                    if(cur_link.title)
                        title = cur_link.title.substr(0, cur_link.title.indexOf("\n"));
                    cur_link.innerText = cur_link.textContent = title;
                }
                for(var j = 0; j < block_users.length; ++j)
                {
                    var block = false;
                    if(cur_link.title && 
                        (cur_link.title.indexOf("作者:" + block_users[j]) != -1 || 
                        cur_link.title.indexOf("作者: " + block_users[j]) != -1) )
                        block = true;
                    else
                    {
                        var author_with_brackets = (cur_author.innerText || cur_author.textContent);
                        var test = /^\[(.*?)\]$/;
                        if(author_with_brackets && 
                            test.test(author_with_brackets) && 
                            block_users[j] == (author_with_brackets).match(
                            test)[1])
                            block = true;
                    }
                    if(block)
                        blockPostInToplist(cur_number, cur_link, cur_author);
                }
                var forum = (cur_link.title.match(/版区:(?:<.*?>)?([^<\s]+)/) 
                || ["", ""])[1];
                if(block_forums.indexOf(forum) != -1)
                    blockPostInToplist(cur_number, cur_link, cur_author);
            }
        }

        filterPosts(list[0]); //最新回复主题
        filterPosts(list[1]); //最新发表主题
        //filterPosts(list[3]); //好友最新主题
    })();

    //Blocking users in thread list
    (location.pathname == "/thread.php") && block_users.length && (function ()
    {
        var hide_authors = true;
        var list = document.getElementsByClassName("tr3 t_one"); //<tr>
        for(var i = 0; i < list.length; ++i)
        {
            var td = list[i].children[2];
            var a = td.children[0];
            var text = a.innerText || a.textContent;
            for(var j = 0; j < block_users.length; ++j)
                if(text == block_users[j])
                {
                    list[i].style.display = "none";
                    break;
                }
        }
    })();

    //Modify post reading pages
    (location.pathname == "/read.php") && 
    (block_users.length || block_signature_users.length || 
        block_photos.length || block_images.length || block_content.length ||
    simple_read) && 
    (function ()
    {
        var dummy = {style:{}};
        var posts = document.getElementsByClassName("t5");
        for(var i = 0; i < posts.length; ++i)
        {
            var div = posts[i];
            var tbody = div.children[0].children[0];
            //                  table       tbody
            var content_tr = tbody.children[0];
            //                          tr.tr1
            if(content_tr.className != "tr1")
                continue;

            var userinfo_th = content_tr.children[0];
            //                              th.r_two
            var username_div = userinfo_th.children[0] || dummy;
            var userhonor_div = getFirstChildByClassName(userinfo_th, "honor") || dummy;
            var userpic_div = getFirstChildByClassName(userinfo_th, "user-pic") || dummy;
            var userdetails_div = 
            (userpic_div || userhonor_div || username_div).
            nextElementSibling || dummy;

            var signature_th = tbody.children[1].children[0];
            //                         tr1 r_one         th
            var signature_line = getFirstChildByClassName(signature_th, "sigline") || dummy;
            var signature_content = getFirstChildByClassName(signature_th, "signature") || dummy;
            var post_actions = getFirstChildByClassName(signature_th, "tipad black") || dummy;
            if(simple_read)
            {
                userpic_div.style.display = "none";
                userhonor_div.style.display = 
                userdetails_div.style.display = 
                signature_line.style.display = 
                signature_content.style.display = "none";
                signature_th.style.paddingTop = "0px";
                post_actions.style.margin = "0 1em 0 1em";
                var username_text_div = getFirstChildByClassName(username_div, "readmagic");
                var username_a = username_text_div.children[0].children[0];
                username_a.style.backgroundColor = "";
            }
            var user = username_div.children[1];
            //                  div.listread.fl
            var username = "";
            if(user)
            {
                username = user.innerText || user.textContent;
                if(block_users.indexOf(username.trim()) != -1)
                {
                    div.style.display = "none";
                    continue;
                }
                if(block_signature_users.indexOf(username.trim()) != -1)
                    signature_content.style.display = "none";
                if(block_photos.indexOf(username.trim()) != -1)
                {
                    var photo_container = content_tr.children[0];
                    for(var j = 0; j < photo_container.children.length; ++j)
                    {
                        if(photo_container.children[j].className == "user-pic")
                        {
                            var img = photo_container.children[j].children[0].
                            children[0].children[0].children[0].children[0].
                            children[0];
                            img.style.display = "none";
                            break;
                        }
                    }
                }
            }

            if(block_images.length == 0 && block_content.length == 0)
                continue;
            //Blocking content or images in content
            var post_th = content_tr.children[1];
            //                      th#td_xxx.r_one
            for(var j = 0; j < post_th.children.length; ++j)
                if(post_th.children[j].className == "tpc_content")
                {
                    if(block_images.indexOf(username.trim()) != -1)
                    {
                        function hideImages(element)
                        {
                            for(var i = 0; i < element.children.length; ++i)
                            {
                                var cur = element.children[i];
                                if(cur.tagName.toLowerCase() == "img")
                                    cur.style.display = "none";
                                else
                                    hideImages(cur);
                            }
                        }
                        hideImages(post_th.children[j]);
                    }

                    if(block_content.length)
                    {
                        var cur = post_th.children[j];
                        var text = ( (cur.innerText || cur.textContent).match(
                        /[\u4e00-\u9fa5]/g) || [] ).join('');
                        for(var k = 0; k < block_content.length; ++k)
                        {
                            if(text == block_content[k])
                            {
                                div.style.display = "none";
                                break;
                            }
                        }
                    }
                    break;
                }
        }
    })();
}

function login_nowait()
{
    var target = $("ul li a")[1].href;

    if (target.match(/^http*/) && target != location.href)
        location.replace(target);
}

function getRedirectUrl(url,cur_domain)
{
    var domainRegEx = /^([^:]+:\/\/)([^\/]+)/;
    var domain_match = url.match(domainRegEx);
    var domain;
    var KnownDomains = [
        "bbs.stuhome.net", 
        "bbs.qshpan.com", 
        "bbs.uestc6.edu.cn", 
        "bbs.germanyt.com", 
        "bbs.tangdg.info", 
        "bbs.auxten.com"
    ];

    if(domain_match && (domain = domain_match[2]) && KnownDomains.indexOf(domain) != -1)
        return url.replace(domainRegEx, "$1" + cur_domain);
    else
        return null;
}

function login_url_replace(data)
{
    var cur_href,cur_domain;

    if(data.auto_domain == "outter") {
        if(data.outter == "qsh")
            cur_domain = "bbs.qshpan.com";
        else
            cur_domain = "bbs.germanyt.com";

        cur_href = getRedirectUrl(location.href,cur_domain);
    } else if(data.auto_domain == "close") {
    } else if(data.auto_domain == "auto") {
        if(data.in_uestc == 1) { /* choose inner */
            if(data.inner == "v4")
                cur_domain = "bbs.stuhome.net";
            else
                cur_domain = "bbs.uestc6.edu.cn";
        } else {
            if(data.outter == "qsh")
                cur_domain = "bbs.qshpan.com";
            else
                cur_domain = "bbs.germanyt.com";
        }
        cur_href = getRedirectUrl(location.href,cur_domain);
    }

    return cur_href;
}

function inner_outter(new_url)
{
    if(new_url != null && new_url != location.href)
        location.href = new_url;
}

function log_page_proc(new_url,data)
{
    var target = $("ul li a")[1];

    if(new_url != null) {
        target.attr("href",new_url);
        redirect(new_url,7);
    }

    if(data.login_nowait == 1)
        login_nowait();
}

function logins_proc(data)
{
    var cur_domain;
    var cur_href;
    var real_login_url = login_url_replace(data);

    if(location.href.match(/^http:\/\/uc\.stuhome\.net\/admin*/)){
        log_page_proc(real_login_url,data);
    } else {
        inner_outter(real_login_url);
    }
}

self.port.on('init_page', function(message) {
    var rm_mainad = message.rm_main_ad;
    var hide_level_2 = message.hide_level_2;
    var rm_bbs_rules = message.rm_bbs_rules;

    if (location.href.match("^http.*ad_if.*") != null)
        return;

    logins_proc(message);

    if(rm_mainad == 1) {
        var iframe = $("iframe");
        for(var i=0;i<iframe.length;i++){
            if(iframe[i].src.indexOf("ad_iframe.php") != -1){
                iframe[i].style.display = "none";
            }
        }
    }

    if(hide_level_2 == 1) {
        if(location.pathname == "/" || location.pathname == "/index.php")
            $("#t_9999").css({"display":"none"});
    }

    if(rm_bbs_rules == 1) {
        if (location.href.indexOf("fid") != -1) {
            var announce_frame = getElementsByClass("t");
            for (var i = 0; i < announce_frame.length; i++) {
                announce_frame[i].style.display = "none";
            }
        }
    }

    blocks_proc(message);
});
